#! /bin/sh

source /etc/rc.d/common

# Stop the LATE user settable services (reverse order)
for i in $(/bin/echo ${LATE_SERVICES} | /usr/bin/tr ' ' '\n' | \
    /usr/bin/tac | /usr/bin/tr '\n' ' '); do
    if check_enabled "${i}"; then
        ${RC_D_PREFIX}/${i} stop
    fi
done

if [ -x /etc/rc.d/rc.network ]; then
    /etc/rc.d/rc.network stop
fi

# Stop the EARLY user settable services (reverse order)
for i in $(/bin/echo ${EARLY_SERVICES} | /usr/bin/tr ' ' '\n' | \
    /usr/bin/tac | /usr/bin/tr '\n' ' '); do
    if check_enabled "${i}"; then
        ${RC_D_PREFIX}/${i} stop
    fi
done

if [ -x /etc/rc.d/rc.syslogd ]; then
    /etc/rc.d/rc.syslogd stop
fi

/bin/echo "Sending all processes the TERM signal..."
/sbin/killall5 -15
/bin/sleep 1

/bin/echo "Sending all processes the KILL signal..."
/sbin/killall5 -9
/bin/sleep 1

/bin/echo "Saving random seed to a temporary file..."
/bin/dd if=/dev/urandom of=/var/lib/esos/random-seed count=1 bs=512 2> /dev/null

/bin/echo "Saving the system time to hardware clock..."
/sbin/hwclock --systohc --utc

# Write wtmp records
case "$0" in
    *6)
        /sbin/reboot -w
    ;;
    *0)
        /sbin/halt -w
    ;;
esac

if ! /bin/grep esos_iso /proc/cmdline > /dev/null 2>&1; then
    /bin/echo "Synchronizing configuration..."
    /usr/local/sbin/conf_sync.sh > /dev/null 2>&1
fi

if ! /bin/grep esos_iso /proc/cmdline > /dev/null 2>&1; then
    /bin/echo "Saving log files..."
    /usr/local/sbin/archive_logs.sh
fi

mdadm --detail --scan | while read -r row; do
    md_path="$(echo ${row} | awk '{ print $2 }')"
    md_name="$(echo ${row} | awk '{ print $4 }' | cut -d= -f2 | cut -d: -f2)"
    if echo ${md_name} | egrep 'esos_boot|esos_root|esos_conf|esos_logs' \
        > /dev/null; then
        mdadm --stop ${md_path}
    fi
done

/bin/echo "Remounting root file system read-only..."
/bin/mount -n -o remount,ro /

/bin/echo "Flushing file system buffers..."
/bin/sync

/bin/echo "Unmounting local file systems..."
/bin/umount -l /dev
/bin/umount -a

case "$0" in
    *6)
        /bin/echo "Rebooting..."
        /sbin/reboot -d -f -i
    ;;
    *0)
        /bin/echo "Bye..."
        /sbin/halt -d -f -p
    ;;
esac
